package com.tarena.lbs.user.dao.repository.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.user.dao.mapper.UserMapper;
import com.tarena.lbs.user.dao.repository.UserRepository;
import com.tarena.lbs.user.pojo.po.UserGroupPO;
import com.tarena.lbs.user.pojo.po.UserPO;
import com.tarena.lbs.user.pojo.query.UserGroupQuery;
import com.tarena.lbs.user.pojo.query.UserQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UserRepositoryImpl implements UserRepository {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserPO getByPhone(String phone) {
        QueryWrapper<UserPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public Long countUserByPhone(String phone) {
        QueryWrapper<UserPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        return userMapper.selectCount(queryWrapper);
    }

    @Override
    public void save(UserPO poParam) {
        userMapper.insert(poParam);
    }

    @Override
    public UserPO getById(Integer userId) {
        return userMapper.selectById(userId);
    }



    @Override
    public PageInfo<UserPO> pageList(UserQuery query) {
        PageHelper.startPage(query.getPageNo(), query.getPageSize());
        QueryWrapper<UserPO> queryWrapper =  assembleUserQuery(query);
        List<UserPO> pos = userMapper.selectList(queryWrapper);// 调用上面的方法
        return new PageInfo<>(pos);
    }


    private QueryWrapper<UserPO> assembleUserQuery(UserQuery query) {
        QueryWrapper<UserPO> queryWrapper = new QueryWrapper<>();
        // 账号模糊查询 - 修正字段名
        if (StringUtils.isNotBlank(query.getUserName())) {
            queryWrapper.like("user_name", query.getUserName()); // 修正为正确的字段名
        }

        // 用户姓名/昵称模糊查询 - 修正字段名
        if (StringUtils.isNotBlank(query.getNickName())) {
            queryWrapper.like("nick_name", query.getNickName());
        }


        // 手机号模糊查询
        if (StringUtils.isNotBlank(query.getPhone())) {
            queryWrapper.like("phone", query.getPhone());
        }

        // 渠道来源精确查询
        if (query.getProviderType() != null) {
            queryWrapper.eq("provider_type", query.getProviderType());
        }

        if (query.getEndTime() != null) {
            queryWrapper.ge("reg_time", query.getStartingTime())
                    .le("reg_time", query.getEndTime());
        }

        // 排除已删除数据
        queryWrapper.eq("is_deleted", 0);

        queryWrapper.orderByDesc("reg_time");
        queryWrapper.orderByDesc("id");

        return queryWrapper;
    }
}
